Java编程题-生成5个不重复的随机数

生成5个不重复的随机数[1-5]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Random;

public class RandomTest02 {

public static void main(String[] args) {

Random r = new Random();

int[] a = new int[5];

int index = 0;

while (index < 5) {
int temp = r.nextInt(6);

if (temp != 0 && !contains(a, temp)) {
a[index++] = temp;
}
}

for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}

}

// 判断temp元素在a数组中是否包含
private static boolean contains(int[] a, int temp) {
for (int i = 0; i < a.length; i++) {
if (a[i] == temp) {
return true;
}
}
return false;
}
}